<template>
  <div class="query-form">
    <el-form
      :model="queryForm"
      ref="queryFormRef"
      label-width="100px"
      :inline="true"
    >
    <el-row>
      <el-col :span="8">
        <el-form-item label="供应商ID" label-width="150px" label-position="right">
        <el-input v-model="queryForm.venderId" placeholder="双击选择供应商" @dblclick="venderDialogVisible = true" style="width: 200px" />
      </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="供应商名称" label-width="150px" label-position="right">
        <el-input v-model="queryDto.venderName"  style="width: 200px" aria-disabled="true" readonly />
      </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="供应商编码" label-width="150px" label-position="right" >
        <el-input v-model="queryDto.venderOpcode"  style="width: 200px" aria-disabled="true" readonly />
      </el-form-item>
      </el-col>
    </el-row>




    <el-row>

      <el-col :span="8">
        <el-form-item label="申请人" label-width="150px" label-position="right" >
        <el-input v-model="queryForm.createrName"  style="width: 200px" aria-disabled="true" />
      </el-form-item>
      </el-col>
      <el-col :span="8">
          <el-form-item label="申请日期" label-width="150px" label-position="right">
          <el-date-picker
            v-model="currentDate"
            type="daterange"
            range-separator="-"
            start-placeholder="起始时间"
            end-placeholder="结束时间"
            style="width: 300px"
          />
          </el-form-item>
      </el-col>
<el-col :span="8">
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button type="success" @click="handlePass">通过</el-button>
            <el-button type="danger" @click="handleReturn">不通过</el-button>
          </el-form-item>
        </el-col>
    </el-row>


    </el-form>



















     <!-- 弹窗查询供应商 -->
    <el-dialog title="选择供应商" v-model="venderDialogVisible" width="700px">
      <el-row :gutter="10" style="margin-bottom: 10px;">
        <el-col :span="16">
          <el-input
            v-model="venderQuery"
            placeholder="请输入供应商名称"
            size="small"
          />
        </el-col>
        <el-col :span="1"/>
        <el-col :span="3">
          <el-button
            type="primary"
            size="small"
            style="width: 100%;"
            @click="venderSearch">
            查询
          </el-button>
        </el-col>
        <el-col :span="2"/>
      </el-row>

      <el-table
        :data="dataVender.list"
        style="width: 100%;"
        @row-click="selectvender">
        <el-table-column prop="comPartyId" label="供应商ID" width="120" />
        <el-table-column prop="partyOpcode" label="供应商代码" />
        <el-table-column prop="partyName" label="供应商名称" />
      </el-table>
       <!-- 分页 -->
      <div style="margin-top: 10px; text-align: right;">
        <el-pagination
          v-model:current-page="dataVender.pageNum"
          v-model:page-size="dataVender.pageSize"
          :total="dataVender.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="venderSearch"
          @current-change="venderSearch"
        />
      </div>
    </el-dialog>
<!-- 申请明细弹窗 -->
    <el-dialog title="申请明细" v-model="applyDialog" width="1500px">
      <el-table
        :data="dataApplyLines.list"
        style="width: 100%;">
        <el-table-column prop="hnyyPurRebatePurHxLId" label="明细ID" width="80" v-if="false" />
        <el-table-column prop="hnyyPurRebatePurListId" label="政策ID" width="80" />
        <el-table-column prop="orderNo" label="进仓单号" width="160" />
        <el-table-column prop="receiverDate" label="进货日期" width="120" :formatter="formatDate"/>
        <el-table-column prop="goodsOpcode" label="品种代码" width="150" />
        <el-table-column prop="goodsName" label="品种名称" width="200"/>
        <el-table-column prop="goodsName" label="品种规格" width="150"/>
        <el-table-column prop="goodsName" label="厂家" width="200"/>
        <el-table-column prop="lotNo" label="批号" width="100"/>
        <el-table-column prop="goodsBatchNo" label="批次" width="200"/>
        <el-table-column prop="channelOpcode" label="渠道" width="100"/>


        <el-table-column prop="taxRate" label="税率" width="100"/>
        <el-table-column prop="taxPrice" label="含税单价" width="100"/>
        <el-table-column prop="actRebAmt" label="可核销金额" width="100"/>
        <el-table-column prop="applyAmt" label="申请核销金额" width="110"/>
        <el-table-column prop="sscPurchaseId" label="进仓单主表ID" width="110"/>
        <el-table-column prop="sscPurchaseLinesId" label="进仓单明细表ID" width="130"/>
      </el-table>
       <!-- 分页 -->
      <div style="margin-top: 10px; text-align: right;">
        <el-pagination
          v-model:current-page="dataVender.pageNum"
          v-model:page-size="dataVender.pageSize"
          :total="dataVender.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="venderSearch"
          @current-change="venderSearch"
        />
      </div>
    </el-dialog>



  </div>
  <div class="table-container">
    <el-table v-fit-columns
      :data="tableDataList.list"
      border
      style="width: 100%"
      :header-cell-style="{
        color: '#333',
        backgroundColor: '#eaf4ff',
        height: '20px'  // 表头固定高度
      }"
      @selection-change="handleSelectionChange"
      :row-style="{ height: '20px' }"
      :cell-style="{ padding: '5px 0' }"
    >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="hnyyPurRebatePurHxId" label="id" width="100" v-if="false"/>
        <el-table-column prop="hnyyPurRebatePurHxNo" label="申请流水号" width="200" />
        <el-table-column prop="venderName" label="供应商名称" width="250" />
        <el-table-column prop="venderCode" label="供应商代码" width="120" />
        <el-table-column prop="createrName" label="申请人" width="100"/>

        <el-table-column
          prop="createDate"
          label="申请日期"
          width="100"
          :formatter="formatDate"
        />
        <el-table-column fixed="right" label="操作" width="100">
          <template #default="scope">
          <el-button @click="applyLines(scope.row)" type="text" size="small">查看明细</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="purMemo" label="采购审核备注" width="100"/>
        <el-table-column label="财务审核备注" width="120">
          <template #default="scope">
            <el-input
              v-model="scope.row.opMemo"
              size="small"
            />
          </template>
        </el-table-column>
      </el-table>
       <!-- 分页 -->
      <div style="margin-top: 10px; text-align: right;">
        <el-pagination
          v-model:current-page="tableDataList.pageNum"
          v-model:page-size="tableDataList.pageSize"
          :total="tableDataList.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleQuery"
          @current-change="handleQuery"
        />
      </div>

  </div>
</template>
























<script setup>
import { reactive, ref,nextTick } from 'vue'
import request from '@/utils/request'
import { ElLoading,ElMessage  } from 'element-plus';
import {currentDate} from '../../utils/time.js';
import dayjs from 'dayjs'


const queryDto = reactive({})

const queryForm = reactive({
  venderId: '',
  createrName:'',
  opFlag:'ACCEPT',
  startDate: currentDate.value[0],
  endDate: currentDate.value[1],
  pageNum: 1,
  pageSize: 20
})
// 日期格式化
const formatDate = (row, column) => {
  const date = row[column.property]
  return date ? dayjs(date).format('YYYY-MM-DD') : ''
}
// 日期格式化
const formatDateHms = (row, column) => {
  const date = row[column.property]
  return date ? dayjs(date).format('YYYY-MM-DD HH:MM:DD') : ''
}
// 供应商弹窗
const venderDialogVisible = ref(false)

//明细弹窗
const applyDialog = ref(false)

// 供应商查询条件
const venderQuery = ref('')


// 主表单分页查询
const tableDataList = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
  list:[]
})

// 供应商分页查询
const dataVender = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0,
  list:[]
})


const dataApplyLines = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0,
  list:[]
})

let loadingInstance = null;

const selectedRows = ref([]) // 存储勾选的行
const handleSelectionChange = (val) => {
  selectedRows.value = val
  // 计算合计
  let actTotal = 0
  let rebTotal = 0

  val.forEach(item => {
    actTotal += Number(item.actRebAmt) || 0
    rebTotal += Number(item.rebAmt) || 0
  })

  // 保留两位
  queryDto.actRebAmtTotal = Number(actTotal.toFixed(2))
  queryDto.rebAmtTotal = Number(rebTotal.toFixed(2))
}


// 供应商查询请求
const venderSearch = () => {
  if (!venderQuery.value) return ElMessage.warning('请输入供应商名称')
  nextTick(() => {
    loadingInstance = ElLoading.service({
      target: '.el-dialog__body',
      text: '加载中...'
    });
  });
  request.get('/link/getVenderList', { params: { name: venderQuery.value ,pageNum:dataVender.value.pageNum,pageSize:dataVender.value.pageSize} }).then((res) => {
    console.log('res=======> ', res)
    if (res.code === 200) {
      dataVender.value.list = res.data.list
      dataVender.value.total = res.data.total
    }
  }).catch((err) => {
      ElMessage.error('详情加载失败');
      console.error(err);
    }).finally(() => {
      if (loadingInstance) loadingInstance.close();
    });
}

//明细查询
const applyLines = (row) =>{
  applyDialog.value = true
  nextTick(() => {
    loadingInstance = ElLoading.service({
      target: '.el-dialog__body',
      text: '加载中...'
    });
  });
console.log('row=======> ', row.hnyyPurRebatePurHxId)
  request.get('/account/getPurHxLines', { params: { hnyyPurRebatePurHxId: row.hnyyPurRebatePurHxId ,pageNum:dataApplyLines.value.pageNum,pageSize:dataApplyLines.value.pageSize} }).then((res) => {
    console.log('res=======> ', res)
    if (res.code === 200) {
      dataApplyLines.value.list = res.data.list
      dataApplyLines.value.total = res.data.total
    }
  }).catch((err) => {
      ElMessage.error('详情加载失败');
      console.error(err);
    }).finally(() => {
      if (loadingInstance) loadingInstance.close();
    });
}

// 供应商数据回填
const selectvender = (row) => {
  queryForm.venderId = row.comPartyId
  queryDto.venderName = row.partyName
  queryDto.venderOpcode = row.partyOpcode
  venderDialogVisible.value = false
}

// 品种数据回填
const selectGoods = (row) => {
  queryForm.goodsId = row.comGoodsId
  queryDto.goodsName = row.goodsName
  queryDto.goodsOpcode = row.goodsOpcode
  goodsDialogVisible.value = false
}


//主表单查询
const handleQuery = () => {
  console.log('queryForm',queryForm)

  queryForm.startDate = dayjs(currentDate.value[0]).format('YYYY-MM-DD')
  queryForm.endDate = dayjs(currentDate.value[1]).format('YYYY-MM-DD')
  request.post('/account/getPurCGCheck', queryForm).then((res) => {
    console.log('res=======> ', res)
    if (res.code === 200) {
      tableDataList.list = res.data.list.map(item => {
        return {
          ...item,
          actRebAmt: item.actRebAmt == null || item.actRebAmt === '' ? item.rebAmt : item.actRebAmt
        }
      })
      tableDataList.total = res.data.total
      tableDataList.pageNum = res.data.pageNum
      tableDataList.pageSize = res.data.pageSize
    }

  }).catch((err) => {
      ElMessage.error('详情加载失败');
      console.error(err);
    });
}



//通过
const handlePass = async () => {
  if (!selectedRows.value.length) {
    ElMessage.warning('请先选择审批的数据')
    return
  }
  const d = []
  try {
    for (const row of selectedRows.value) {

      d.push({hnyyPurRebatePurHxId:row.hnyyPurRebatePurHxId,opMemo:row.opMemo})

    }
    // 所有都执行完毕后再刷新
    request.post('/account/purCwPass', d).then(res => {
    console.log('res',res)
    if (res.code === 200) {
      ElMessage.success('审核通过')
      handleQuery()
    } else {
      ElMessage.error('审核失败')
    }
  }).catch(err => {
    console.error(err)
    ElMessage.error('审核异常')
  })

  } catch (err) {
    console.error(err)
    ElMessage.error('批量审核过程中出现异常')
  }
}


</script>
